package com.frontop.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.frontop.common.domain.UserJurisdiction;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.nio.charset.StandardCharsets;

public class JwtUtil {
    /**
     * 获取JWT中token内容信息
     * @param authentication
     * @return {
     *         "aud": [
     *             "system-service"
     *         ],
     *         "user_name": "yj",
     *         "jwt-ext": "JWT 扩展信息",
     *         "scope": [
     *             "all"
     *         ],
     *         "exp": 1639035757,
     *         "authorities": [
     *             "ROLE_ADMIN"
     *         ],
     *         "jti": "47cd9584-1d5c-4009-a6b7-27a36f252f91",
     *         "client_id": "app-client"
     *     }
     */
    public static Claims getJwtInfo(Authentication authentication){
        authentication.getCredentials();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        String jwtToken = details.getTokenValue();
        Claims claims = Jwts.parser()
                .setSigningKey("sign-8888".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(jwtToken)
                .getBody();
        return claims;
    }

    public static UserJurisdiction getUserJurisdiction(Authentication authentication){
        Claims claims = getJwtInfo(authentication);
        UserJurisdiction  userJurisdiction = JSON.parseObject(JSON.toJSONString(claims.get("jwt-userJurisdiction")), new TypeReference<UserJurisdiction>() { });
        return userJurisdiction;
    }


}
